import axios from 'axios'
import store from '@/store'
import { getToken } from '@/utils/auth'

/*
|--------------------------------------------------------------------------
| PHPService 定义
|--------------------------------------------------------------------------
| 用于调用PHP API
|
*/

window.canCancelAxios = []

// create an PHP axios instance
const phpService = axios.create({
  baseURL: process.env.VUE_APP_PHP_API // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  // timeout: 5000 // request timeout
})

// request interceptor
phpService.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers.Authorization = 'Bearer ' + getToken()
    }

    const whiteList = [] // 白名单
    if (config.url && whiteList.every(item => !config.url.includes(item))) {
      config.cancelToken = new axios.CancelToken(function (c) {
        window.canCancelAxios.push({ key: config.key || '', cancel: c })
      })
    }
    return config
  },
  error => {
    // do something with request error
    console.log('phpService.interceptors.request Error', error) // for debug
    return Promise.reject(error, 'phpService.interceptors.request Error')
  }
)

// response interceptor
phpService.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    // if the custom code is not 0, it is judged as an error.
    if (res.code > 0) {
      // 20103: token无效
      if (res.code === 20103 || res.code === 10401) {
        // to re-login
        // 如果token无效，取消后续请求
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      }

      if (res.code === 10302) {
        location.reload(true)
      }

      return Promise.reject(res)
    } else {
      return res
    }
  },
  error => {
    console.log('phpService.interceptors.response Error' + error) // for debug
    // Message({
    //   message: '服务器请求失败，请稍后再试',
    //   type: 'error',
    //   duration: 5 * 1000
    // })
    return Promise.reject(error)
  }
)

export default phpService
